package pro.softzhang.algo.lc200;

import pro.softzhang.algo.common.TreeNode;

public class LC297_SerializeAndDeserializeBinaryTree {
    public static void main(String[] args) {
        TreeNode root = new TreeNode();
        Codec codec = new Codec();
        String s  = codec.serialize(root);
        TreeNode root2 = codec.deserialize(s);
    }

    static class Codec {

        private int idx = 0;

        public String serialize(TreeNode root) {
            if(root == null) {
                return "#";
            }

            return root.val + "," + serialize(root.left) + "," + serialize(root.right);
        }

        public TreeNode deserialize(String data) {
            String[] nodeStrArr = data.split(",");
            return deserialize0(nodeStrArr);
        }

        private TreeNode deserialize0(String[] strs) {
            String nodeStr = strs[idx++];
            if("#".equals(nodeStr)) {
                return null;
            }
            TreeNode node = new TreeNode(Integer.parseInt(nodeStr));
            node.left = deserialize0(strs);
            node.right = deserialize0(strs);
            return node;
        }
    }
}